<template>
  <el-form>
    <!-- 订单审批内容 -->
    <el-card
      v-if="queryParams.type == 'purchaseapply'"
      shadow="never"
      style="margin-top: 1%"
    >
      <template #header>
        <span>云采附件</span>
      </template>
      <el-form label-width="180px">
        <div class="projectOrderPart">
          <!-- 跳转详情页 -->
          <el-button style="margin-left: 2%" @click="showDetailPage()"
            >项目订单详情</el-button
          >
          <!-- 项目订单附件 -->
          <el-row style="margin-top: 2%">
            <el-col :span="24">
              <el-form-item label="项目订单附件" required>
                <div
                  v-if="
                    pjectOdModel.projectOrderFile &&
                    pjectOdModel.projectOrderFile.length > 0
                  "
                  style="display: inline-block"
                >
                  <el-button
                    v-for="(file, index) in pjectOdModel.projectOrderFile"
                    :key="index"
                    type="text"
                    @click="windowOpenView('projectOrderFile', file.fileUrl)"
                  >
                    {{ file.fileOriginName }}
                  </el-button>
                </div>
                <span v-else style="font-size: small; color: grey"
                  >暂无文件</span
                >
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 云采项目附件 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="云采项目附件" required>
                <el-upload
                  v-model:file-list="pjctYcFile"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="pjctYcFileHandleSuccess"
                  :before-remove="pjctYcFileBeforeRemove"
                  multiple
                  style="width: 80%"
                >
                  <el-button :icon="Upload" color="#1E3485">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="crossRope" style="margin-top: 1%" />
        <div class="supplyOrderPart">
          <!-- 跳转详情页 -->
          <el-button
            style="margin-left: 2%; margin-top: 2%"
            @click="
              toDetail(
                {
                  id: pjectOdModel.supplyOrderId,
                  title: pjectOdModel.supplyOrderName,
                  action: 'view'
                },
                'supplyapply'
              )
            "
            >供货订单详情</el-button
          >
          <!-- 供货订单附件 -->
          <el-row style="margin-top: 2%">
            <el-col :span="24">
              <el-form-item label="供货订单附件" required>
                <el-button
                  type="text"
                  @click="
                    showFilePreview(pjectOdModel.supplyOrderId, 'supplyOrder')
                  "
                >
                  {{ pjectOdModel.supplyOrderName }} 预览/下载
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 云采供货附件 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="云采供货附件" required>
                <el-upload
                  v-model:file-list="splyYcFile"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="splyYcFileHandleSuccess"
                  :before-remove="splyYcFileBeforeRemove"
                  multiple
                  style="width: 80%"
                >
                  <el-button :icon="Upload" color="#1E3485">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-card>
    <!-- 正常审批内容 -->
    <el-card shadow="never" style="margin-top: 1%">
      <template #header>
        <span>审批</span>
        <closeTagButton id="closeTagButtonRef" style="display: none" />
        <el-button
          v-show="isNeedShowRouteInExamine"
          color="#1E3485"
          size="small"
          @click="showDetailPage()"
          >查看详情</el-button
        >
      </template>
      <el-form :model="examineModel" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核批准" style="width: 100%">
              <el-radio-group v-model="examineModel.auditResult">
                <el-radio value="1">同意</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核退回" style="width: 100%">
              <el-radio-group v-model="examineModel.auditResult">
                <el-radio value="2">发起人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批意见" style="width: 100%">
              <el-input
                v-model="examineModel.text"
                :rows="2"
                type="textarea"
                placeholder="请输入 审批意见"
              />
              <vxe-button mode="text" @click="examineModel.text = '同意'"
                >同意</vxe-button
              >
              <vxe-button mode="text" @click="examineModel.text = '不同意'"
                >不同意</vxe-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批附件" style="width: 100%">
              <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :action="uploadUrl"
                :headers="headers"
                multiple
                :on-preview="handlePreview"
                :on-success="handleSuccess"
                style="width: 80%"
              >
                <el-button :icon="Upload" color="#1E3485">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">文件大小不能超过10M</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-button color="#1E3485" @click="examineApproval()"
              >确认</el-button
            >
            <el-button @click="handleClose()">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 弹窗类 -->
    <div class="dialogs">
      <filePreview
        :visible="filePreviewVisible"
        :fileId="fileId"
        :fileType="fileType"
        :fileUrl="fileUrl"
        @close="closeFilePreview"
      />
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile, UploadFile } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import closeTagButton from "@/components/closeTagButton.vue";
import filePreview from "@/components/filePreview.vue";
import { useRoute } from "vue-router";
import { useDetail } from "./utils/hooks";
import type { ProjectOrderModel } from "./type/type";
import { headers, uploadUrl } from "@/api/utils";
import { saleContractApproval } from "@/api/ERP_sales";
import { procureContractApproval } from "@/api/ERP_procure";
import { purchaseapplyApproval } from "@/api/ERP_OrderManage";
import {
  reconciliationApproval,
  reconciliationSettlementApproval,
  spreconciliationApproval,
  spreconciliationSettlementApproval
} from "@/api/ERP_settlement";
import {
  paymentApprovalApi,
  receivePaymentApprovalApi
} from "@/api/ERP_PaymentMange";
import {
  getAuditFileInfoForPjctOd,
  saveAuditFileInfoForPjctOd
} from "@/api/ERP_public";

///////////////////////// 公共 /////////////////////////
// 路由传参
const route = useRoute();
const { toDetail } = useDetail();
const queryParams = route.query;
// 查看详情
let isNeedShowRouteInExamine =
  queryParams.type == "purchaseapply" ? false : true;
///////////////////////// 数据准备/查看 /////////////////////////
// 表单数据
const pjectOdModel: ProjectOrderModel = reactive({
  bidId: "", // 项目订单id
  supplyOrderId: "", // 供货订单id
  supplyOrderSn: "", // 供货订单编号
  supplyOrderName: "", // 供货订单名称
  supplyOrderFile: [], // 供货订单附件
  projectOrderFile: [], // 项目订单附件
  supplyOrderCloudFile: [], // 供货订单云采附件
  projectOrderCloudFile: [] // 项目订单云采附件
});
const examineModel = reactive({
  auditResult: "1",
  text: "",
  auditFileList: ""
});
// 上传文件相关
let fileList = ref<UploadUserFile[]>([]);
let pjctYcFile = ref<UploadUserFile[]>([]);
let splyYcFile = ref<UploadUserFile[]>([]);
let examineFileList = [];
let projectOrderCloudFileList = [];
let suppltOrderCludFileList = [];
const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};
const handleSuccess = uploadFileList => {
  examineFileList.push(uploadFileList.data);
  const formatterObj = [];
  for (let i in examineFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = examineFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      examineFileList[i].name.substring(
        examineFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = examineFileList[i].name;
    formatterObj.push(tempvalue);
  }
  examineModel.auditFileList = JSON.stringify(formatterObj);
};
const pjctYcFileHandleSuccess = uploadFileList => {
  projectOrderCloudFileList.push(uploadFileList.data);
  const formatterObj = [];
  for (let i in projectOrderCloudFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = projectOrderCloudFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      projectOrderCloudFileList[i].name.substring(
        projectOrderCloudFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = projectOrderCloudFileList[i].name;
    formatterObj.push(tempvalue);
  }
  pjectOdModel.projectOrderCloudFile = formatterObj;
};
const pjctYcFileBeforeRemove = (uploadFile: UploadFile) => {
  let fileItems = pjectOdModel.projectOrderCloudFile;
  fileItems.forEach((item, index) => {
    if (item.fileOriginName == uploadFile.name) {
      fileItems.splice(index, 1);
    }
  });
  pjectOdModel.projectOrderCloudFile = fileItems;
  return true;
};
const splyYcFileHandleSuccess = uploadFileList => {
  suppltOrderCludFileList.push(uploadFileList.data);
  const formatterObj = [];
  for (let i in suppltOrderCludFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = suppltOrderCludFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      suppltOrderCludFileList[i].name.substring(
        suppltOrderCludFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = suppltOrderCludFileList[i].name;
    formatterObj.push(tempvalue);
  }
  pjectOdModel.supplyOrderCloudFile = formatterObj;
};
const splyYcFileBeforeRemove = (uploadFile: UploadFile) => {
  let fileItems = pjectOdModel.supplyOrderCloudFile;
  fileItems.forEach((item, index) => {
    if (item.fileOriginName == uploadFile.name) {
      fileItems.splice(index, 1);
    }
  });
  pjectOdModel.supplyOrderCloudFile = fileItems;
  return true;
};
// 预览/下载 弹窗
let filePreviewVisible = ref(false);
let fileId = ref("");
let fileType = ref("");
let fileUrl = ref("");
function showFilePreview(id: string, type: string) {
  fileId.value = id;
  fileType.value = type;
  filePreviewVisible.value = true;
}
function closeFilePreview(val: boolean) {
  filePreviewVisible.value = val;
}
function showDetailPage() {
  switch (queryParams.type) {
    case "salecontract":
      toDetail(
        { id: queryParams.id, title: queryParams.title },
        "salecontract"
      );
      break;
    case "purchasecontract":
      toDetail(
        { id: queryParams.id, title: queryParams.title },
        "purchasecontract"
      );
      break;
    case "purchaseapply":
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "purchaseapply"
      );
      break;
    case "reconciliation":
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "reconciliation"
      );
      break;
    case "reconciliationSettlement":
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "reconciliationSettlement"
      );
      break;
    case "spreconciliation":
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "spreconciliation"
      );
      break;
    case "spreconciliationSettlement":
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "spreconciliationSettlement"
      );
      break;
    case "receive": // 收款管理
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "receive"
      );
      break;
    case "payment": //付款款管理
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "payment"
      );
      break;
    case "ElevatorOrder": //电梯订单
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "ElevatorOrder"
      );
      break;
    case "PurchaseContractAdvancePayment": //采购合同预付款
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "PurchaseContractAdvancePayment"
      );
      break;
    case "SalesContractAdvancePayment": //销售合同预收款
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "SalesContractAdvancePayment"
      );
      break;
    case "ProjectOrderAdvancePayment": //项目订单预收款
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "ProjectOrderAdvancePayment"
      );
      break;
    case "SupplyOrderAdvancePayment": //供货订单预付款
      toDetail(
        { id: queryParams.id, title: queryParams.title, action: "view" },
        "SupplyOrderAdvancePayment"
      );
      break;
    // case "收款管理":
    //   break;
    // case "付款管理":
    //   break;
    default:
      ElMessage.error(
        "详情页面： " + queryParams.type + " 正在开发中，暂不支持审批"
      );
      break;
  }
}
// 文件预览
function windowOpenView(type: string, fileUrl: string) {
  if (type === "projectOrderFile") {
    window.open(fileUrl, "_blank");
  }
}
///////////////////////// 数据请求 /////////////////////////
// 获取项目订单相关文件
async function getProjectOrderFiles() {
  let params: ApiParams = {};
  params.bizId = queryParams.id;
  const response: ApiResponse = await getAuditFileInfoForPjctOd(params);
  if (response.code === 200) {
    for (let key in pjectOdModel) {
      pjectOdModel[key] = response.data[key];
    }
    pjctYcFile.value = response.data.projectOrderCloudFile.map(file => ({
      name: file.fileOriginName,
      url: file.fileUrl
    }));
    splyYcFile.value = response.data.supplyOrderCloudFile.map(file => ({
      name: file.fileOriginName,
      url: file.fileUrl
    }));
  } else {
    ElMessage.error("获取项目订单相关附件信息失败");
  }
}
// 项目订单类，云采附件上传
async function saveProjectOrderFiles() {
  // 判空
  if (
    pjectOdModel.projectOrderCloudFile == null ||
    pjectOdModel.projectOrderCloudFile.length == 0 ||
    pjectOdModel.supplyOrderCloudFile == null ||
    pjectOdModel.supplyOrderCloudFile.length == 0
  ) {
    ElMessage.error("请上传项目订单相关云采附件！");
    return false;
  }
  // 数据准备
  let params: ApiParams = {};
  params.bizId = queryParams.id;
  params.projectOrderCloudFile = pjectOdModel.projectOrderCloudFile;
  params.supplyOrderCloudFile = pjectOdModel.supplyOrderCloudFile;
  const response: ApiResponse = await saveAuditFileInfoForPjctOd(params);
  if (response.code && response.code === 200) {
    ElMessage.success("保存项目订单相关云采附件成功");
  } else {
    ElMessage.error("保存项目订单相关附件信息失败");
    return false;
  }
}
// 审批请求
async function examine() {
  let params: ApiParams = {};
  params.id = queryParams.id;
  if (examineModel.auditResult === "1") {
    params.auditResult = true;
  } else {
    params.auditResult = false;
  }
  params.auditResultMsg = examineModel.text;
  params.auditFileList = examineModel.auditFileList;
  let response: ApiResponse;
  // 根据类型分类审批接口
  switch (queryParams.type) {
    // 销售合同
    case "salecontract":
      response = await saleContractApproval(params);
      break;
    // 采购合同
    case "purchasecontract":
      response = await procureContractApproval(params);
      break;
    // 项目订单
    case "purchaseapply":
      response = await purchaseapplyApproval(params);
      break;
    // 项目对账单
    case "reconciliation":
      response = await reconciliationApproval(params);
      break;
    // 项目结算单
    case "reconciliationSettlement":
      response = await reconciliationSettlementApproval(params);
      break;
    // 供应商对账单
    case "spreconciliation":
      response = await spreconciliationApproval(params);
      break;
    // 供应商结算单
    case "spreconciliationSettlement":
      response = await spreconciliationSettlementApproval(params);
      break;
    case "receive":
      response = await receivePaymentApprovalApi(params);
      break;
    case "payment": // 付款管理
      response = await paymentApprovalApi(params);
      break;
    default:
      ElMessage.error(
        "审批类型： " + queryParams.type + " 正在开发中，暂不支持审批"
      );
      break;
  }
  if (response.code === 200) {
    document.getElementById("closeTagButtonRef").click();
    ElMessage({
      showClose: true,
      message: "审批完成",
      type: "success"
    });
  } else {
    ElMessage({
      showClose: true,
      message: "审批失败：" + response.msg,
      type: "error"
    });
  }
}
// 审批按钮
async function examineApproval() {
  if (queryParams.type === "purchaseapply") {
    const shouldContinue = await saveProjectOrderFiles();
    if (shouldContinue === false) {
      return;
    }
  }
  await examine();
}
// 取消按钮
function handleClose() {
  document.getElementById("closeTagButtonRef").click();
  ElMessage.warning("已取消");
}
///////////////////////// 公共 /////////////////////////
// 初始化
onMounted(async () => {
  // 审核类型为项目订单时，获取审批文件
  if (queryParams.type === "purchaseapply") {
    await getProjectOrderFiles();
  }
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
}
.header-span {
  display: flex;
  align-items: center;
}
.item {
  display: flex;
  align-items: center;
  margin-left: 20px;
  font-size: 12px;
}
.container {
  height: 20px;
  width: 80px;
  text-align: center;
  border: 1px solid #eee;
  line-height: 20px;
  font-size: 12px;
  margin-right: 6px;
  border-radius: 20px;
}
::v-deep(.el-row) {
  justify-content: center;
}
</style>
